﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using ChuanYe.CountyFireManagement.EF.MySQL.Models;
using Microsoft.EntityFrameworkCore;
using ChuanYe.CountyFireManagement.Model;
using ChuanYe.Core.Utils;
using ChuanYe.CountyFireManagement.EF.MySQL;

namespace ChuanYe.CountyFireManagement.BLL
{
    public class FireHeadquarterMemberBLL
    {
        #region 构造单例
        private FireHeadquarterMemberBLL() { }
        private static FireHeadquarterMemberBLL _instance;
        public static FireHeadquarterMemberBLL Instance
        {
            get
            {
                return _instance ?? (_instance = new FireHeadquarterMemberBLL());
            }
        }
        #endregion

        public List<dynamic> Get(int headquarterId) 
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var linq = from a in ef.Fireheadquartermember select a;
                if (headquarterId>0)
                {
                    linq = linq.Where(p => p.HeadquarterId == headquarterId);
                }
                var linq2 = from a in linq.OrderBy(p => p.TransDatetime).ToList()
                            join b in ef.Fireheadquarter on a.HeadquarterId equals b.HeadquarterId
                            into c
                            let d = c.FirstOrDefault()
                            join e in ef.Fireteamdepartment on a.TeamDepartmentId equals e.TeamDepartmentId
                            into f
                            let g = f.FirstOrDefault()
                            join h in ef.Position on a.PositionId equals h.PositionId
                            into i 
                            let j=i.FirstOrDefault()
                            select new 
                            {
                                a.HeadquarterMemberId,
                                a.Name,
                                a.Phone,
                                a.PositionId,
                                a.TeamDepartmentId,
                                a.Tel,
                                a.TransDatetime,
                                a.HeadquarterId,
                                HeadquarterName=d==null?string.Empty:d.Name,
                                TeamDepartmentName=g==null ? string.Empty : g.Name,
                                PositionName=j==null?string.Empty:j.PositionName
                            };
                return linq2.ToList<dynamic>();
            }
        }

        public int Add(Fireheadquartermember info)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var exist = ef.Fireheadquartermember.Where(p => p.Name == info.Name).FirstOrDefault();
                if (exist != null)
                {
                    return -2;
                }
                ef.Fireheadquartermember.Add(info);
                ef.Entry<Fireheadquartermember>(info).State = EntityState.Added;
                ef.SaveChanges();
                return 1;
            }
        }

        public ResultDto<dynamic, dynamic> GetByPage(RequestPageBase page)
        {
            ResultDto<dynamic, dynamic> result = new ResultDto<dynamic, dynamic>();
            var sql = AppSetting.GetConfig("Sql:FireHeadquarterMemberBLL.GetByPage");
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                string paramsSql = string.Empty;

                if (!string.IsNullOrEmpty(page.Keyword))
                {
                    paramsSql += $" a.Name like '%{page.Keyword}%'";
                    paramsSql += $" or b.Name like '%{page.Keyword}%'";
                    paramsSql += $" or c.Name like '%{page.Keyword}%'";
                    paramsSql = $" and ({paramsSql})";
                }
                paramsSql += page.OrderByPattern == 0 ? "a.TransdateTime".OrderByDescending() : "a.TransdateTime".OrderBy();
                paramsSql += page.Limit();
                sql = string.Format(sql, paramsSql);
                var countSql = sql.CountSql();
                var list = ef.Database.SqlQuery<FireheaDquarterMemberModel>(sql);
                result.FirstParam = list;
                result.SecondParam = ef.Database.SqlQuery(countSql).Rows[0][0];
            }
            return result;
        }

        public int Update(Fireheadquartermember info)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var exist = ef.Fireheadquartermember.Where(p => p.HeadquarterMemberId == info.HeadquarterMemberId).FirstOrDefault();
                if (exist == null)
                {
                    return -1;
                }
                else
                {
                    exist.HeadquarterMemberId = info.HeadquarterMemberId;
                    exist.HeadquarterId = info.HeadquarterId;
                    exist.TeamDepartmentId = info.TeamDepartmentId;
                    exist.Tel = info.Tel;
                    exist.Name = info.Name;
                    exist.PositionId = info.PositionId;
                    exist.TransDatetime = info.TransDatetime;
                    exist.Phone = info.Phone;
                    ef.Fireheadquartermember.Add(exist);
                    ef.Entry<Fireheadquartermember>(exist).State = EntityState.Modified;
                    return ef.SaveChanges();
                }
            }
        }

        public int Remove(int headquarterMemberId)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {

                var exist = ef.Fireheadquartermember.Where(p => p.HeadquarterMemberId == headquarterMemberId).FirstOrDefault();
                if (exist == null)
                {
                    return -1;
                }

                //是否被成立前指所占用
                var ffcAllList =ef.Firefrontcommand.Select(s => new { s.FireId,s.HeadquarterMemberIds }).ToList();
                var existFirefrontcommand = ffcAllList.Where(p=>!string.IsNullOrEmpty(p.HeadquarterMemberIds))
                                            .Select(s => new { HeadquarterMemberIds=s.HeadquarterMemberIds.Split(',').ToList()
                                            }).ToList().Where(p=>p.HeadquarterMemberIds.Contains(headquarterMemberId.ToString())).FirstOrDefault();
                if (existFirefrontcommand != null)
                {
                    return -2;
                }
                ef.Fireheadquartermember.Add(exist);
                ef.Entry<Fireheadquartermember>(exist).State = EntityState.Deleted;
                return ef.SaveChanges();
            }
        }
    }
}
